package com.denlaku.longan.service.impl;

import com.denlaku.longan.anno.RequiredTx;
import com.denlaku.longan.qo.Query;
import com.denlaku.longan.repository.TenantMemberRepository;
import com.denlaku.longan.service.TenantMemberService;
import com.denlaku.longan.service.UserService;
import com.denlaku.longan.util.SnowflakeUtils;
import com.denlaku.longan.vo.TenantMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author tianx
 */
@Service
public class TenantMemberServiceImpl implements TenantMemberService {
	@Autowired
	private TenantMemberRepository tenantMemberRepository;

	@Autowired
	private UserService userService;

	@Override
	public List<TenantMember> list(TenantMember tenantMember) {
		return tenantMemberRepository.list(tenantMember);
	}

	@Override
	public TenantMember get(Long tenantId, Long userId) {
		TenantMember tenantMember = tenantMemberRepository.get(tenantId, userId);
		Optional.ofNullable(tenantMember).map(TenantMember::getUserId)
			.map(userService::get).ifPresent(user -> {
				tenantMember.setUsername(user.getName());
				tenantMember.setAccount(user.getAccount());
			});
		return tenantMember;
	}

	@Override
	public boolean exists(Long tenantId, Long userId) {
		return tenantMemberRepository.exists(tenantId, userId);
	}

	@Override
	@RequiredTx
	public void add(TenantMember tenantMember) {
		tenantMember.setId(SnowflakeUtils.nextId());
		tenantMemberRepository.add(tenantMember);
	}

	@Override
	@RequiredTx
	public void update(TenantMember tenantMember) {
		tenantMemberRepository.update(tenantMember);
	}

	@Override
	@RequiredTx
	public void delete(Query query) {
		tenantMemberRepository.delete(query);
	}

}
